package com.seewo.dubbo.debugger.core;


import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.fastjson.JSON;
import com.seewo.dubbo.debugger.api.ApiDebuggerService;
import com.seewo.dubbo.debugger.api.DataType;
import com.seewo.dubbo.debugger.api.Request;
import com.seewo.dubbo.debugger.api.Result;
import com.seewo.dubbo.debugger.api.model.ApiDef;
import com.seewo.dubbo.debugger.api.model.Document;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * @author chenliangliang
 * @date 2018/7/26
 */
@Slf4j
public class ApiDebuggerServiceImpl implements ApiDebuggerService {

    private ApiInvoker apiInvoker = new ApiInvoker();

    @Override
    public Map<String, Document> getDocs() {
        return ApiContext.getApis();
    }

    @Override
    public Document getDoc(String interfaceName) {
        return getDocs().get(interfaceName);
    }


    @Override
    public ApiDef getApi(String interfaceName, String methodName) {
        Document doc = getDoc(interfaceName);
        for (ApiDef apiDef : doc.getApiList()) {
            if (apiDef.getMethodName().equals(methodName)) {
                return apiDef;
            }
        }
        return null;
    }

    @Override
    public Result debug(Request request) {
        try {
            Object result = apiInvoker.invoke(request);
            Class<?> clazz = result == null ? Void.class : result.getClass();
            String type = DataType.getType(clazz);
            if ("object".equals(type)) {
                return Result.ok(JSON.toJSONString(result, true));
            } else {
                return Result.ok(result);
            }
        } catch (Exception e) {
            log.error("{} 调试失败", RpcContext.getContext().getRemoteAddressString(), e);
            return Result.fail(e.getMessage());
        }
    }
}
